package com.tianji.learning.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tianji.api.client.user.UserClient;
import com.tianji.api.dto.user.UserDTO;
import com.tianji.common.domain.dto.PageDTO;
import com.tianji.common.utils.BeanUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.learning.domain.dto.ReplyDTO;
import com.tianji.learning.domain.po.InteractionQuestion;
import com.tianji.learning.domain.po.InteractionReply;
import com.tianji.learning.domain.vo.ReplyVO;
import com.tianji.learning.enums.QuestionStatus;
import com.tianji.learning.mapper.InteractionReplyMapper;
import com.tianji.learning.query.ReplyPageQuery;
import com.tianji.learning.service.IInteractionQuestionService;
import com.tianji.learning.service.IInteractionReplyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 互动问题的回答或评论 服务实现类
 * </p>
 *
 * @author gml
 * @since 2024-06-25
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class InteractionReplyServiceImpl extends ServiceImpl<InteractionReplyMapper, InteractionReply> implements IInteractionReplyService {
    private final IInteractionQuestionService questionService;
    private final UserClient userClient;
    /**
     * 新增互动回复
     *
     * @param replyDTO
     */
    @Override
    public void saveReply(ReplyDTO replyDTO) {
        log.info("新增互动回复：{}", replyDTO);
        // 1.复制属性
        InteractionReply interactionReply = BeanUtils.copyBean(replyDTO, InteractionReply.class);
        // 2.添加用户id
        interactionReply.setUserId(UserContext.getUser());
        // 3.保存
        save(interactionReply);
        //4.补充评论信息
        //4.1如果是回答则修改问题的回答数
        if (ObjectUtil.isEmpty(replyDTO.getAnswerId())){
            questionService.lambdaUpdate()
                    .setSql("answer_times = answer_times + 1")
                    .setSql("latest_answer_id = " + interactionReply.getId())
                    .eq(InteractionQuestion::getId, replyDTO.getQuestionId())
                    .update();
        }
        //4.2如果是评论则修改回答的评论数
        if (ObjectUtil.isNotEmpty(replyDTO.getAnswerId())){
            lambdaUpdate()
                    .setSql("reply_times = reply_times + 1")
                    .eq(InteractionReply::getId, replyDTO.getAnswerId())
                    .update();
        }
        //4.3如果是老师的回答或评论则改为已查看
        if (!replyDTO.getIsStudent()){
            questionService.lambdaUpdate()
                    .set(InteractionQuestion::getStatus, QuestionStatus.CHECKED)
                    .eq(InteractionQuestion::getId, replyDTO.getQuestionId())
                    .update();
        }
    }

    /**
     * 分页查询互动回复
     *
     * @param query
     * @return
     */
    @Override
    public PageDTO<ReplyVO> getReplyPage(ReplyPageQuery query) {
        log.info("分页查询互动回复：{}", query);
        //1.参数校验

        //2.分页查询
        Page<InteractionReply> page = lambdaQuery()
                .eq(ObjectUtil.isNotEmpty(query.getQuestionId()), InteractionReply::getQuestionId, query.getQuestionId())
                .eq(ObjectUtil.isNotEmpty(query.getAnswerId()), InteractionReply::getAnswerId, query.getAnswerId())
                .page(query.toMpPageDefaultSortByCreateTimeDesc());
        List<InteractionReply> records = page.getRecords();
        if (ObjectUtil.isEmpty(records)){
            return PageDTO.empty(page);
        }
        //3.补充信息查询
        //3.1远程调用查询回答者信息,上一级回复者信息,被回复者信息
        List<Long> replyIds = new ArrayList<>();
        for (InteractionReply record : records) {
            if (ObjectUtil.isNotEmpty(record.getUserId())){
                replyIds.add(record.getUserId());
            }
            if (ObjectUtil.isNotEmpty(record.getTargetUserId())){
                replyIds.add(record.getTargetUserId());
            }
        }
        Map<Long, UserDTO> userMap = new HashMap<>();
        if (ObjectUtil.isNotEmpty(replyIds)){
            List<UserDTO> userDTOS  = userClient.queryUserByIds(replyIds);
            if (ObjectUtil.isNotEmpty(userDTOS)){
                userMap = userDTOS.stream().collect(Collectors.toMap(UserDTO::getId, Function.identity()));
            }
        }

        //4.封装VO
        List<ReplyVO> replyVOS = new ArrayList<>();
        for (InteractionReply record : records) {
            ReplyVO replyVO = BeanUtils.copyBean(record, ReplyVO.class);
            //4.1补充回答者信息和被回复者信息
            if (ObjectUtil.isNotEmpty(userMap)){
                UserDTO userDTO = userMap.get(record.getUserId());
                if (ObjectUtil.isNotEmpty(userDTO)){
                    replyVO.setUserName(userDTO.getName());
                    replyVO.setUserIcon(userDTO.getIcon());
                }
                UserDTO userDTO1 = userMap.get(record.getTargetUserId());
                if (ObjectUtil.isNotEmpty(userDTO1)) {
                    log.info("被回复者信息：{}", userDTO1.getName());
                    replyVO.setTargetUserName(userDTO1.getName());
                }
            }
            //4.2补充点赞信息

            replyVOS.add(replyVO);
        }
        //5.组装返回
        return PageDTO.of(page, replyVOS);
    }

    /**
     * 修改互动回复是否隐藏
     * @param id
     * @param hidden
     */
    @Override
    public void updateReply(Long id, Boolean hidden) {
        this.update().eq("id", id).set("hidden", hidden).update();
    }
}
